package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BaseAccessoryConfigBean;
import com.koron.css2.baseConfig.bean.PubAccessoryTypeBean;
import com.koron.css2.baseConfig.mapper.BaseAccessoryCofingMapper;
import com.koron.css2.baseConfig.mapper.PubAccessoryTypeMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AccessoryQueryByReceiptType implements ServerInterface{

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		// TODO Auto-generated method stub
		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);
		try {
			BaseAccessoryConfigBean bean = JsonUtils.objectToPojo(req.getData(), BaseAccessoryConfigBean.class);
			BaseAccessoryCofingMapper mapper = factory.getMapper(BaseAccessoryCofingMapper.class);
			List<BaseAccessoryConfigBean> list = mapper.selectByReceiptType2(bean.getReceiptType());

			PubAccessoryTypeMapper pmapper =  factory.getMapper(PubAccessoryTypeMapper.class,"_default");
			// 先把公共库所有的附件类型查询出来
			List<PubAccessoryTypeBean> accessoryTypeList = pmapper.selectList();
			// 转成Map
			Map<String, PubAccessoryTypeBean> accessoryTypeMap = accessoryTypeList.stream().collect(Collectors.toMap(PubAccessoryTypeBean::getAccessoryNo, Function.identity()));
			//转换附件类型
			for (BaseAccessoryConfigBean baseAccessoryConfigBean : list) {
				PubAccessoryTypeBean access = accessoryTypeMap.get(baseAccessoryConfigBean.getAccessoryNo());
				if(access!=null && StringUtils.isNotEmpty(access.getAccessoryName())) {
					baseAccessoryConfigBean.setAccessoryType(access.getAccessoryName());
					baseAccessoryConfigBean.setSortNo(access.getSortNo());
					baseAccessoryConfigBean.setPjType(access.getPjType());
				}
			}
			list=list.stream().sorted(Comparator.comparing(BaseAccessoryConfigBean::getSortNo)).collect(Collectors.toList());
			info.setData(list);
		}catch(Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("操作失败");
			logger.error("操作失败", e);
		}
		return info;
	}
}
